package com.admin.controller.admin;

import com.github.pagehelper.PageInfo;
import com.system.annotation.Log;
import com.system.constant.HTTPStatus;
import com.system.emus.BusinessType;
import com.system.entity.Role;
import com.system.entity.Teacher;
import com.system.response.Result;
import com.system.service.RoleService;
import com.system.service.TeacherService;
import com.system.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author zfc
 * @since 2023-04-20
 */
@RestController
@RequestMapping("/teacher")
@Log4j
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/list")
    @ApiOperation("教师列表")
    public Result list(@RequestBody Map<String, Object> map) {

        PageInfo pageInfo = teacherService.teacherLimit(map);
        return new Result().setCode(HTTPStatus.SUCCESS).setData(pageInfo);
    }

    @GetMapping("/all")
    @ApiOperation("所有教师数据")
    public Result all() {
        return teacherService.teacherAll();
    }

    @Log(title = "用户管理",businessType = BusinessType.INSERT)
    @RequiresPermissions("admin:teacher:insert")
    @PostMapping("/addTeacher")
    @ApiOperation("新增教师")
    public Result add(@RequestBody Teacher teacher) {
        Teacher teahcerAllById = teacherService.getTeacherByUserName(teacher.getUsername());

        if (!StringUtils.isNull(teahcerAllById)) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("用户名【" + teacher.getUsername() + "】已存在！");
        } else {
            boolean addTeahcer = teacherService.addTeahcer(teacher);
            if (addTeahcer) {
                return new Result().setCode(HTTPStatus.SUCCESS).setMessage("用户【" + teacher.getUsername() + "】新增成功。");
            } else {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("用户【" + teacher.getUsername() + "】新增失败，请联系管理员。");
            }
        }
    }

    @Log(title = "用户管理",businessType = BusinessType.FREEZE)
    @RequiresPermissions("admin:teacher:freeze")
    @DeleteMapping("/batchUpdateTeacherIsDelete")
    @ApiOperation("删除教师（修改用户IsDelete状态）")
    public Result batchUpdateTeacherIsDelete(@RequestParam("ids") Integer ids[],
                                             @RequestParam("isDelete") Integer isDelete) {
        return teacherService.batchUpdateTeacherIsDelete(ids, isDelete);
    }

    @Log(title = "用户管理",businessType = BusinessType.DELETE)
    @RequiresPermissions("admin:teacher:remove")
    @DeleteMapping("/batchDeleteTeacherById")
    @ApiOperation("彻底删除教师")
    public Result batchDeleteTeacherById(Integer[] ids) {
        return teacherService.batchDeleteTeacherById(ids);
    }

    @Log(title = "用户管理",businessType = BusinessType.RESERT)
    @RequiresPermissions("admin:teacher:resetTeacherPwd")
    @PutMapping("/resetTeacherPwd")
    @ApiOperation("重置用户密码")
    public Result resetTeacherPwd(@RequestBody Teacher teacher) {
        return teacherService.resetTeacherPwd(teacher);
    }

    @GetMapping("/selectTeacherById")
    @ApiOperation("查询教师通过编号")
    public Result selectTeacherById(Integer id) {
        Teacher teahcerById = teacherService.selectTeahcerAllById(id);
        return new Result().setCode(HTTPStatus.SUCCESS).setData(teahcerById);
    }

    @Log(title = "用户管理",businessType = BusinessType.UPDATE)
    @PutMapping("/updateTeacher")
    @ApiOperation("修改教师信息")
    public Result updateTeacher(@RequestBody Teacher teacher) {
        boolean updateTeacher = teacherService.updateTeacher(teacher);
        Teacher updateTer = null;
        if (updateTeacher) {
            updateTer = teacherService.selectTeahcerById(teacher.getId());
            updateTer.setPassword("******");
            SecurityUtils.getSubject().getSession().setAttribute("teacher", updateTer);
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("用户【" + updateTer.getName() + "】修改成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("用户【" + updateTer.getName() + "】修改失败，请联系管理员。");
        }
    }

    @PutMapping("/updatePassword")
    @ApiOperation("Teacher修改密码")
    public Result updatePassword(@RequestParam("id") Integer id,
                                 @RequestParam("password") String password,
                                 @RequestParam("former") String former) {
        Teacher teacher = new Teacher();
        teacher.setId(id);
        teacher.setPassword(password);
        //检查输入的旧密码是否正确
        boolean b = teacherService.checkFormerPasswordFlag(teacher, former);
        if (!b) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("旧密码错误");
        }

        boolean unique = teacherService.checkTeacherPasswordUnique(teacher);
        if (unique) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("新密码不能和旧密码一致");
        } else {
            boolean updateTeacher = teacherService.upadteTeacherPassword(teacher);

            if (updateTeacher) {
                SecurityUtils.getSubject().logout();
                return new Result().setCode(HTTPStatus.SUCCESS).setMessage("密码修改成功，请重新登录。");
            } else {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("密码修改失败，请联系管理员。");
            }
        }
    }

    //------------------------------------教师 - 关联 - 角色-----------------------------------------------

    @GetMapping("/queryTeacherBoundRoles")
    @ApiOperation("通过教师编号查询教师已绑定角色")
    public Result queryTeacherBoundRoles(@RequestParam("teacherId") Integer teacherId){
        Set<Role> teacherRoles = roleService.queryTeacherBoundRoles(teacherId);
        return new Result().setCode(HTTPStatus.SUCCESS).setData(teacherRoles);
    }
    @Log(title = "用户管理",businessType = BusinessType.GRANT)
    @RequiresPermissions("admin:teacher:teacherBoundRoles")
    @PostMapping("/teacherBoundRoles")
    @ApiOperation("教师绑定角色（可以批量绑定角色）")
    public Result teacherBoundRoles(@RequestParam("teacherId") Integer teacherId,
                                    @RequestParam("roleIds") Integer[] roleIds) {
        return roleService.teacherBoundRoles(teacherId, roleIds);
    }

}
